package org.dfl.plugin.editor.actions;

import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.dfl.core.data.IODataManager;
import org.dfl.core.data.Token;
import org.dfl.core.model.Place;
import org.dfl.messages.Messages;
import org.dfl.plugin.DflPlugin;
import org.dfl.plugin.ProjectConstraints;
import org.dfl.plugin.dialogs.DialogsManager;
import org.dfl.plugin.editor.model.DflDiagram;
import org.dfl.plugin.utils.WorkbenchUtil;
import org.eclipse.core.resources.IProject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchPart;

/**
 * load the flow state from a file action
 * @author Piotr Wlodarczyk
 *
 */
public class LoadAllTokensAction extends org.eclipse.gef.ui.actions.SelectionAction {
	public static final String ACTION_ID = "LoadAllTokensAction"; //$NON-NLS-1$
	private DflDiagram diagram;

	public LoadAllTokensAction(IWorkbenchPart part, DflDiagram diagram) {
		super(part);
		this.diagram = diagram;
		setId(ACTION_ID);
		setImageDescriptor(DflPlugin.getImageDescriptor("icons/eclipse/load.gif")); //$NON-NLS-1$
		setHoverImageDescriptor(getImageDescriptor());
		setText(Messages.LoadAllTokensAction_0);
		setToolTipText(Messages.LoadAllTokensAction_1);
	}

	protected boolean calculateEnabled() {
		return (diagram!=null && diagram.isRunnning()) ;
	}

	public void run() {
		// change the perspective
		Map<Place, Collection<Token>> tokensMap = load(diagram);
		if (tokensMap == null) {
			return;
		} else if (tokensMap.isEmpty()) {
			DialogsManager.openErrorDialog(Messages.LoadAllTokensAction_2);
		}

		diagram.pause();
		synchronized (DflPlugin.class) {
			diagram.clearData();
			Set<Place> places = tokensMap.keySet();
			for (Place place : places) {
				Collection<Token> tokens = tokensMap.get(place);
				for (Token token : tokens) {
					place.addToken(token);
				}
			}
		}
	}

	private Map<Place,Collection<Token>> load(DflDiagram diagram) {
		FileDialog dlg = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SINGLE);
        
		IProject project = WorkbenchUtil.getCurrentProject();
		String projectPath = project.getLocation().toFile().getAbsolutePath();
		if(new File(projectPath + ProjectConstraints.PROJECT_DIR_STATES).exists()){ //$NON-NLS-1$
			dlg.setFilterPath(projectPath + ProjectConstraints.PROJECT_DIR_STATES); //$NON-NLS-1$
		}else{
			dlg.setFilterPath(projectPath);
		}
		
        // Change the title bar text
        dlg.setText(Messages.LoadAllTokensAction_3);

        // null if user cancels
        String fileName = dlg.open();
        if (fileName != null) {
        	try {
        		return IODataManager.loadDiagramTokens(fileName, diagram);
			} catch (Exception e) {
				DialogsManager.openErrorDialog(e);
			}
        }
        return null;
	}
}
